<?php 
namespace app\api\model;

use libraries\BaseModel;
use libraries\SystemCodes;
use libraries\Tools;
use libraries\PHPMailer\PHPMailer;

/**
 * 邮件模型
 */
class Mail extends BaseModel
{

    function __construct($data = [])
    {
        parent::__construct($data);

    }

    /**
	 * [send description]
	 * @Author QiaoWeiWei
	 * @Date   2019-11-22
	 * @param  [array|string]        $receiver      [收件人邮箱]
	 * @param  [array|string]     	 $receiver_nick [收件人名称]
	 * @param  [string]     		 $subject       [邮件主题]
	 * @param  [string]     		 $body          [邮件正文]
	 * @return [type]       		              [description]
	 */
	function send($receiver,$receiver_nick,$subject,$body){
		if(empty($receiver)){
			return Tools::set_result(SystemCodes::EMAIL_RECEIVER_IS_EMPTY[0],SystemCodes::EMAIL_RECEIVER_IS_EMPTY[1]);
		}
		if(empty(config('email.dsn'))){
            return Tools::set_result(SystemCodes::EMAIL_DSN_IS_EMPTY[0],SystemCodes::EMAIL_DSN_IS_EMPTY[1]);
        }
        $email_nickname = config('email.dsn.nickname');//平台邮箱名称

		$mail = new PHPMailer;
		$mail->isSMTP();
        //$mail->SMTPDebug = 2;    								// 调试模式
        $mail->Host = config('email.dsn.host');					// 邮件服务器地址
        $mail->SMTPAuth = true;									// 允许 SMTP 认证 
        $mail->CharSet = "UTF-8";								// 编码格式
        $mail->Username = config('email.dsn.username');		    // SMTP 用户名  即邮箱的用户名
        $mail->Password = config('email.dsn.pwd');			    // SMTP 密码 
        $mail->SMTPSecure = 'ssl';                    			// TLS或者ssl协议
        $mail->Port = 465;                            			// 服务器端口 25 或者465 具体要看邮箱服务器支持 
        $mail->setFrom(config('email.dsn.username'), $email_nickname);
        if(is_array($receiver)){
            //多个收件人
            foreach ($receiver as $key => $val){
                $mail->addAddress($val, $receiver_nick[$key]);
            }
        }else{
        	//单个收件人
            $mail->addAddress($receiver, $receiver_nick);
        }

        $mail->isHTML(true);        //是否以HTML文档格式发送
        $mail->Subject = $subject;
        $mail->Body = $body; //发送带有html标签文本
        // $mail->AltBody = ''; //如果邮件客户端不支持HTML则显示此内容
        // $mail->addCC(); // 添加抄送
        // $mail->addBCC(); // 添加密送
        // $mail->addAttachment("2e3f19fd-8e3f-405b-9854-41dd19ddebf8.jpg"); // 添加附件

        if(!$mail->send()){
            return Tools::set_result(SystemCodes::EMAIL_SEND_FAILED[0],SystemCodes::EMAIL_SEND_FAILED[1].'：'.$mail->ErrorInfo);
        }
        return Tools::set_result(SystemCodes::SUCCESS[0],SystemCodes::SUCCESS[1]);
	}

}